﻿using AiSk.Sdks;
using System.Text.Json;
using static AiSk.Sdks.AntSkApiService;

namespace AiSk.Impl
{
    public class AntSkService : BaseLLmService
    {
        private record AntSkStreamResponse(string id, string @object, AntSkStreamChoiceItem[]? choices, long created)
        {
            public string GetResponseMessage()
            {
                var choice = choices?.FirstOrDefault();
                if (choice == null) return string.Empty;
                return choice.delta?.content ?? string.Empty;
            }
        }
        private record AntSkStreamChoiceItem(int index, AntSkStreamChoiceItemDelta delta);
        public record AntSkStreamChoiceItemDelta(string role, string? content);
        public async override Task Chat(string question, string system, string model = "")
        {
            var url = "http://192.168.66.76:5000/api/v1/chat/completions";
            var token = "sk-11ee5f7a-dc78-4ae5-9630-94a5740e6326";
            var isStream = true;
            var res = await AntSkApiService.ExecuteChat(url, token, question, "", isStream);
            if (res == null)
            {
                Console.WriteLine($"AIGC未返回内容");
                return;
            }
            if (isStream)
            {
                var r = res as Stream;
                using var reader = new StreamReader(r);
                while (!reader.EndOfStream)
                {
                    var line = await reader.ReadLineAsync();
                    if (string.IsNullOrWhiteSpace(line))
                        continue;
                    Console.WriteLine($"流式返回结果 {line}");
                    var subLine = line.Substring("data: ".Length - 1);
                    Console.WriteLine($"流式返回 subLine:{subLine}");
                    if (subLine == " [DONE]")
                    {
                        return;
                    }
                    try
                    {
                        var lineObj = JsonSerializer.Deserialize<AntSkStreamResponse>(subLine);
                        Console.WriteLine($"流式返回结果 {lineObj.GetResponseMessage()}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"流式返回异常 {subLine} {ex.Message}");
                    }
                }
                return;
            }
            else
            {
                var r = res as AntSkResponseMessage;
                Console.WriteLine($"非流式返回结果 {r.GetResponseMessage()}");
            }
            return;
        }
    }
}
